package cn.javabb.admin.controller.sys;

import cn.javabb.common.model.ResponseModel;
import cn.javabb.common.utils.ListUtils;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.entity.sys.DictDO;
import cn.javabb.core.service.sys.DictService;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/dict")
public class DictAdminController  extends BaseController {

    @Autowired
    private DictService dictService;
    @GetMapping("/list")
    public String toListPage(Model model) {
        return "admin/system/dict";
    }
    /**
     * 菜单保存页面
     * @author QINB
     * @param model
     * @return
     */
    @GetMapping("/save")
    public String toSavePage(Model model) {
        return "admin/system/dictSave";
    }

    @ResponseBody
    @GetMapping("/")
    public Object list() {
        String page = getPage();
        String size = getSize();
        String dictName = getParamValue("dictName");
        DictDO dict = new DictDO();
        if(StringUtils.isNotBlank(dictName)){
            dict.setDictName(dictName);
        }
        Page dictPage = dictService.queryPageByWhere(page, size, dict);
        return ResponseModel.table(dictPage);
    }
    /**
     * 更新
     * @param dict
     * @return
     */
    @ResponseBody
    @PostMapping("/")
    public Object saveOrUpdate(DictDO dict){
        int n = 0;
        if(null == dict.getId()){
            if(null == dict.getState()){dict.setState(1);}
            n = dictService.insertSelective(dict);
        }else{
            n = dictService.updateSelective(dict);
        }
        if(n>0){
            return ResponseModel.Success("保存成功");
        }
        return ResponseModel.Failure("保存失败");

    }

    /**
     * 删除
     * @param dictId
     * @return
     */
    @ResponseBody
    @DeleteMapping("/{navId}")
    public Object delete(@PathVariable String dictId){
        if(StringUtils.isBlank(dictId)){
            return ResponseModel.Failure("参数错误");
        }
        List<String> idList = ListUtils.stringToListString(dictId);
        int num = dictService.deleteByIds(DictDO.class, "id", idList);
        if(num>0){
            return ResponseModel.Success("删除成功");
        }
        return ResponseModel.Failure("删除失败");
    }

    /**
     * 更新状态
     * @param navId
     * @param state
     * @return
     */
    @ResponseBody
    @PostMapping("/updateState")
    public Object updateState(Integer navId,Integer state){
        if(dictService.updateState(navId,state)){
            return ResponseModel.Success("状态更新成功");
        }
        return ResponseModel.Failure("状态更新失败");
    }

}
